<template>
  <div class="experiment-info-table">
    <el-form :model="queryForm" ref="queryFormRef" label-width="90px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="实验时间">
            <el-date-picker
                v-model="experimentTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="炉子编号">
            <el-input v-model="queryForm.heatNo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="生长编号">
            <el-input v-model="queryForm.growNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="催化剂批号">
            <el-input v-model="queryForm.catalystBn"></el-input>
          </el-form-item>
        </el-col>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="danger" @click="resetQuery">重置</el-button> <!-- 添加重置按钮 -->
        <el-button type="primary" @click="exportExcel">导出 Excel</el-button> <!-- 添加导出 Excel 按钮 -->
      </el-row>
    </el-form>
    <p></p>
    <el-table :data="tableData" border style="width: 100%" :stripe="['#f0f9ff', '#fff']">
      <el-table-column label="序号" width="50" align="center">
        <template v-slot="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="dtime" label="实验时间" width="90"></el-table-column>
      <el-table-column prop="pmodel" label="产品型号" width="100"></el-table-column>
      <el-table-column prop="heatNo" label="炉编号" width="80"></el-table-column>
      <el-table-column prop="growNo" label="生长编号" width="120"></el-table-column>
      <el-table-column prop="catalystBn" label="催化剂批号" width="90"></el-table-column>
      <el-table-column prop="catalystQt" label="催化剂目数" width="100"></el-table-column>
      <el-table-column prop="catalystIr" label="催化剂投料量 (g)" width="90"></el-table-column>
      <el-table-column prop="carrierT" label="碳源种类" width="100"></el-table-column>
      <el-table-column prop="carbonsT" label="载气种类" width="100"></el-table-column>
      <el-table-column prop="carrierD" label="载气密度 (g/L)" width="90"></el-table-column>
      <el-table-column prop="carbonsD" label="碳源密度 (g/L)" width="90"></el-table-column>
      <el-table-column prop="hydrogenD" label="氢气密度 (g/L)" width="90"></el-table-column>
      <el-table-column prop="note" label="备注" width="90"></el-table-column>
      <el-table-column prop="carrierTotal" label="载气总量 (g)" width="90"></el-table-column>
      <el-table-column prop="hydrogenTotal" label="氢气总量 (g)" width="90"></el-table-column>
      <el-table-column prop="carbonsTotal" label="碳源总量 (g)" width="90"></el-table-column>
      <el-table-column prop="waterTotal" label="用水总量 (g)" width="90"></el-table-column>
      <el-table-column prop="carbonnTotal" label="碳管总量 (g)" width="90"></el-table-column>
      <el-table-column prop="carbonU" label="碳源利用率（%）" width="90"></el-table-column>
      <el-table-column prop="magnification" label="倍率" width="90"></el-table-column>
      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template v-slot="scope">
          <el-button type="primary" @click="detail(scope.row.id)" >阶段详情</el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    />
    <ExperimentInfoTableSept :row-id="selectedRowId" v-if="dialogVisible" @close="dialogVisible = false"/>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref} from 'vue';
import {ElMessageBox} from "element-plus";
import emitter from "@/utils/eventBus.ts";

// 接口定义
interface TableDataItem { }
interface QueryForm {
  heatNo?: string;
  growNo?: string;
  catalystBn?: string;
  dtimeStart?: string;
  dtimeEnd?: string;
}

export default defineComponent({
  components: {
    ExperimentInfoTableSept: () => import('@/components/LabRecord/ExperimentInfoTableSept.vue')
  },
  setup() {
    let experimentTime = ref([])
    const {proxy}: any = getCurrentInstance()
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const tableData = ref<TableDataItem[]>([])
    const queryForm = ref<QueryForm>({})
    const queryFormRef = ref<typeof import('element-plus')['FormInstance']>()
    const selectedRowId = ref<number | null>(null);
    const dialogVisible = ref(false);



    // 获取数据函数
    const fetchData = async () => {
      try {
        if (experimentTime.value.length > 0) {
          queryForm.value.dtimeStart = experimentTime.value[0].toISOString().slice(0, 19).replace('T', ' ');
          queryForm.value.dtimeEnd = experimentTime.value[1].toISOString().slice(0, 19).replace('T', ' ');
        } else {
          queryForm.value.dtimeStart = '';
          queryForm.value.dtimeEnd = '';
        }
        let param = {
          page: currentPage.value,
          pageSize: pageSize.value,
          ...queryForm.value
        };
        const response = await proxy.$api.ExperimentUrl['list'](param);
        if (response && response.result!== null) {
          tableData.value = response.records;
          total.value = response.total;
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    const handleSizeChange = (val: number) => {
      pageSize.value = val;
      fetchData();
    };

    const handleCurrentChange = (val: number) => {
      currentPage.value = val;
      fetchData();
    };

    const handleQuery = () => {
      currentPage.value = 1;
      fetchData();
    };

    onMounted(() => {
      fetchData();
    });

    const resetQuery = async () => {
      experimentTime.value = []
      queryForm.value.heatNo = ''
      queryForm.value.growNo = ''
      queryForm.value.catalystBn = ''
      fetchData()
    }
    //阶段详情
    const detail = (id) => {
      selectedRowId.value = id;
      dialogVisible.value = true;
    };
    //保存为模板
    const saveAsTemplateBtn = async (id) => {
      ElMessageBox.prompt('保存为模板', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        // 在这里处理用户输入的数字，例如添加新的实验阶段
        templateName.value = value
        await proxy.$api.TemplateUrl['add']({
          "euid": id,
          "heatNo": "C",
          "tname": templateName.value
        });
      }).catch(() => {

      })
    }

    const exportExcel = async () => {
      try {
        const params = {
          ...queryForm.value
        }
        const response = await proxy.$api.ExperimentUrl['exportExecl'](params); // 假设后台接口名为 export
        const blob = new Blob([response], {type: 'application/vnd.ms-excel'});
        const fileName = '输出信息生产.xlsx'; // 这里可以根据接口返回的文件名动态设置，或者自己定义一个合适的文件名

        // 创建一个临时的<a>标签用于下载
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        URL.revokeObjectURL(link.href);
      } catch (error) {
        console.error('Error fetching stage details:', error);
      }
    };

    return {
      currentPage,
      pageSize,
      total,
      tableData,
      queryForm,
      queryFormRef,
      experimentTime,
      handleSizeChange,
      handleCurrentChange,
      handleQuery,
      resetQuery,
      detail,
      exportExcel,
      saveAsTemplateBtn,
      selectedRowId,
      dialogVisible
    };
  },
});
</script>